package com.bandaotixi.cashier.api.business;

import cn.hutool.crypto.digest.MD5;
import com.bandaotixi.cashier.api.business.bo.FileInfo;
import org.aspectj.util.FileUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 对象存储服务接口层
 *
 */
public interface FileService {

    default FileInfo uploadFile(byte[] data, String name) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
        return uploadFile(inputStream, name, true);
    }

    default FileInfo uploadFile(InputStream inputStream, String key) {
        return uploadFile(inputStream, key, true);
    }

    default FileInfo uploadMD5(byte[] data, String suffix) {
        String md5 = MD5.create().digestHex(data);
        return uploadFile(new ByteArrayInputStream(data), "md5/" + md5 + "." + suffix, false);
    }

    /**
     * 计算文件md5再上传，如果存在就不覆盖
     *
     * @param suffix 后缀不带点
     */
    default FileInfo uploadMD5(InputStream inputStream, String suffix) {
        try {
            byte[] data = FileUtil.readAsByteArray(inputStream);
            return uploadMD5(data, suffix);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传文件
     *
     * @return 文件信息
     */
    FileInfo uploadFile(InputStream inputStream, String key, boolean override);

    boolean deleteFile(String key);

    boolean exists(String key);

    FileInfo get(String key);

}
